package nyangweb.shop.start;

import java.lang.reflect.Field;
import java.util.Locale;

import nyangweb.shop.R;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ApplicationErrorReport.AnrInfo;
import android.content.ClipData.Item;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.internal.view.menu.MenuView.ItemView;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;


public class MainActivity extends SherlockFragmentActivity {
	
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private String[] mPlanetTitles;
	private WebView webView;
	private ProgressBar mPBar;
	private int finish_count = 0;
	
	ActionMode mMode;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {	
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainactivity);
		
         
       
		// 액션바숨기기 일단 주석 : 스플릿모드 때문에
		//getSupportActionBar().hide();;
	    
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		
		webView = (WebView) findViewById(R.id.webView1);
		mPBar = (ProgressBar) findViewById(R.id.progress01);
		WebSettings set = webView.getSettings();
		
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl("http://shop-open.co.kr/m/"); // 보여주고자 하는 주소
		
		set.setCacheMode(WebSettings.LOAD_NO_CACHE);
		set.setSupportZoom(false);
		
		webView.setWebViewClient(new WebClient());
		
		webView.setWebChromeClient(new WebChromeClient()        
		{
			 public void onProgressChanged(WebView view, int progress) {
				 if (progress<100)
				 {
					 mPBar.setVisibility(ProgressBar.VISIBLE);                   
				 }                   
				 else if (progress==100)                   
				 {                       
					 mPBar.setVisibility(ProgressBar.GONE);                   
				 }                   
				 mPBar.setProgress(progress);                 
				 }           	
		 
		 });
		
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		
		Field mDragger;
		try {
			mDragger = mDrawerLayout.getClass().getDeclaredField(
			        "mLeftDragger");
		
		mDragger.setAccessible(true);
		ViewDragHelper draggerObj = (ViewDragHelper) mDragger
		        .get(mDrawerLayout);

		Field mEdgeSize = draggerObj.getClass().getDeclaredField(
		        "mEdgeSize");
		
		mEdgeSize.setAccessible(true);
		int edge = mEdgeSize.getInt(draggerObj);

		mEdgeSize.setInt(draggerObj, edge * 2);

		
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//mRightDragger for right obviously
		catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		  getTitle();
	      mPlanetTitles = getResources().getStringArray(R.array.planets_array);
	      mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
	      mDrawerList = (ListView) findViewById(R.id.listview_drawer);
		
		
	      // set a custom shadow that overlays the main content when the drawer opens
	     //   mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
	        // set up the drawer's list view with items and click listener
	        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
	                R.layout.list, mPlanetTitles));
	        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
	        
	        // enable ActionBar app icon to behave as action to toggle nav drawer
	        //getActionBar().setDisplayHomeAsUpEnabled(true);

	        
	        if (savedInstanceState == null) {
	          //  selectItem(0);
	        }
	        
	}


	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
            if(webView.canGoBack())
            {
            	webView.goBack();
            }
            else
            {
            	initialize_count();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);

 	}
	
	private void initialize_count()
    {
		finish_count++;
		
    	if(finish_count ==1)
    	{
    		Toast.makeText(this, "한번 더 누르시면 종료 됩니다.", Toast.LENGTH_SHORT).show();
    		
    		Handler handler =    new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    finish_count = 0; 
                }
            };

            	handler.sendEmptyMessageDelayed(0, 2000);    //  Toast 시간만큼
    	}
    	else if(finish_count == 2)
    	{
    		webView.clearCache(false);
    		finish();
    	}
		
        
    }
	
	

	private class WebClient extends WebViewClient { 
        @Override 
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            
        	if (url.startsWith("sms:")) {
        	     Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
        	     startActivity(i);
        	     return true;
        	    }
        	
        	if (url.startsWith("kakaolink:")) {
        	     Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        	     startActivity(i);
        	     return true;
        	    }
        	      	
        			        	
        	if(url.startsWith("tel")){
                    Intent i = new Intent(Intent.ACTION_DIAL);
                    i.setData(android.net.Uri.parse(url));
                    startActivity(i);
                    
            } else {
                    view.loadUrl(url);            
            } 
            return true;
        }
	}
	


	public void Drawer(){
		if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			mDrawerLayout.openDrawer(mDrawerList);
		}
	}

	

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if (item.getItemId() == android.R.id.home) {
			Drawer();
		}
    	
    	else if(item.getTitle() == "Prev")
    	{
    		webView.goBack();
    	}
    	else if(item.getTitle() == "Next")
    	{
    		webView.goForward();
    	}
    	else if(item.getTitle() == "Home")
    	{
    		webView.loadUrl("http://shop-open.co.kr/m/");
    	}
    	else if(item.getTitle() == "Refresh")
    	{
    		webView.reload();
    	}
    	
            return super.onOptionsItemSelected(item);    
    }
    

    
    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
    	
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	 selectItem(position);
        }
    }
    
    
    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);    
        
    }
    
//    @Override
//    public void setTitle(CharSequence title) {
//        mTitle = title;
//        getActionBar().setTitle(mTitle);
//    }


    /**
     * Fragment that appears in the "content_frame", shows a planet
     */
    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

        	View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);
            String planet = getResources().getStringArray(R.array.planets_array)[i];

            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                            "drawable", getActivity().getPackageName());
            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        //Used to put dark icons on light action bar
        boolean isLight = R.style.Theme_Sherlock == R.style.Theme_Sherlock_Light;

        menu.add("Prev")
            .setIcon(isLight ? R.drawable.ic_compose_inverse : R.drawable.split_prev)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        menu.add("Next")
        .setIcon(isLight ? R.drawable.ic_compose_inverse : R.drawable.split_next)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        
        menu.add("Home")
         .setIcon(isLight ? R.drawable.ic_compose_inverse : R.drawable.home)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        menu.add("Refresh")
            .setIcon(isLight ? R.drawable.ic_refresh_inverse : R.drawable.ic_refresh)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;
    }
    




	public void setContent(TextView view) {
		// TODO Auto-generated method stub
		view.setText(R.string.action_items_content);
	}
	
	
}



